package triangleWorm;

import processing.core.PApplet;
import processing.core.PVector;

public class StickWorm implements IWorm{
	//Parent
	PApplet p;
	
	//Worm movement
	IWormMovement m;
	
	//Worm 'parts'	
	float wormLenth = 200;
	int elementNum = 20;	
	PVector[] elements = new PVector[elementNum];
	float elementMaxDist = wormLenth / (float) elementNum;
	float elementMinDist = elementMaxDist / 20;
	float elementChangeDist = elementMinDist;
	
	//Colors
	int[] elementColors = new int[elementNum];
	float averageColorIntensity = 150;
	float sumOfColorIntensity = averageColorIntensity * 3;
	
	public StickWorm(){
		//Init parts
		for(int i = 0; i < elementNum; i ++) {
			elements[i] = new PVector();
		}
	}

	public void init(PApplet processing, IWormMovement movement) {
		//Get parent
		p = processing;
		
		//Get movement
		m = movement;
		
		//Setup parts
		for(int i = 0; i < elements.length; i ++) {
			//Position
			elements[i].set(m.getPosition());
			
			//Color			
			elementColors[i] = getColor();
		}		
	}

	public void update() {
		//Update movement
		m.update();
		
		//If distance from first element if too big
		if(m.getPosition().dist(elements[0]) > elementChangeDist) {	
			
			//Change values of all elements
			for(int i = elements.length - 1; i > 0; i --) {
				elements[i].set(elements[i - 1]);
				elementColors[i] = elementColors[i - 1];
			}
			
			//Set position and color of first element
			elementColors[0] = getColor();
			elements[0].set(m.getPosition());
			
			elementChangeDist = p.random(elementMinDist, elementMaxDist);
		}
	}

	public void draw() {
		//Iterate over all elements
		for(int i = 1; i < elementNum; i ++) {
			//Set color
			p.stroke(elementColors[i]);
			
			if(i == 1) {
				
			} else {
				p.stroke(elementColors[i]);
				p.line(elements[i].x, elements[i].y, elements[i].z, elements[i - 1].x, elements[i - 1].y, elements[i - 1].z);
				p.noStroke();
			}
		}
	}

	public PVector getPosition() {
		return m.getPosition();
	}
	
	public float getLength() {
		return wormLenth;
	}
	
	private int getColor() {
		//Setup color
		float colorPart1 = sumOfColorIntensity;
		float colorPart2 = sumOfColorIntensity;
		//Get random intervals
		while(colorPart1 >= colorPart2 || colorPart1 > 255f || colorPart2 - colorPart1 > 255f || sumOfColorIntensity - colorPart2 > 255f) {
			colorPart1 = p.random(sumOfColorIntensity);
			colorPart2 = p.random(sumOfColorIntensity);
		}
		//
		float red = colorPart1;
		float green = colorPart2 - colorPart1;
		float blue = sumOfColorIntensity - colorPart2;
		
		return p.color(red, green, blue);
	}

}